﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LeakView.view.controls;
using LeakView.service;
using LeakView.common;

namespace LeakView.misc.view.controls
{
    public partial class HistoryLJSJ : UserControl
    {
        public HistoryLJSJ()
        {
            InitializeComponent();
        }

        private void HistoryLJSJ_Load(object sender, EventArgs e)
        {
            this.comboBox1.SelectedIndex = 0;

            IniAnyConfig config = AnyConfigs.get("APP");
            string headName = config.get("HeadName").GetOrDefault("上游");
            string tailName = config.get("TailName").GetOrDefault("下游");
            this.dataGridView1.Columns[1].HeaderText = headName + " 累积流量";
            this.dataGridView1.Columns[2].HeaderText = tailName + " 累积流量";
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            if (!this.historyTimeRanger1.IsValid)
            {
                MessageBox.Show("参数错误，起始时间必须小于结束时间！", "错误");
                return;
            }

            try
            {
                using (new LoadingStarter())
                {
                    LoadData();
                }
            }
            catch
            {
                MessageBox.Show("获取数据失败，请确定服务器是否正常！", "错误");
            }

        }

        private void LoadData()
        {
            this.dataGridView1.Rows.Clear();

            var date = this.historyTimeRanger1.Date;

            var tailLL = MiscModal.me.LoadHistory(MiscType.Tail15M, date.Year, date.Month, date.Day);
            var headLL = MiscModal.me.LoadHistory(MiscType.Head15M, date.Year, date.Month, date.Day);
            _ = 1;

            var start = this.historyTimeRanger1.StartTime;
            var end = this.historyTimeRanger1.EndTime;

            int minutes = 15;
            switch (this.comboBox1.SelectedIndex)
            {
                case 0:
                    break;
                case 1:
                    minutes = 30;
                    break;
                case 2:
                    minutes = 60;
                    break;
                case 3:
                    minutes = 120;
                    break;
                default:
                    minutes = 15;
                    break;
            }

            DateTime time = start;
            while (time < end)
            {

                var millis = Tools.ConvertDataTimeToLong(time);
                var offset = minutes * 60 * 1000;

                var LL_TAIL = Calculate(tailLL, millis, offset);
                var LL_HEAD = Calculate(headLL, millis, offset);
                var LL_DELTA = LL_TAIL - LL_HEAD;

                var temp = time.AddMinutes(minutes);
                var text = String.Format("{0} {1}-{2}", time.ToString("yyyy-MM-dd"), time.ToString("HH:mm"), temp.ToString("HH:mm"));

                var dgv = this.dataGridView1;
                int idx = dgv.Rows.Add();   //添加行
                dgv.Rows[idx].Cells[0].Value = text;
                dgv.Rows[idx].Cells[1].Value = LL_HEAD.ToString("F3");
                dgv.Rows[idx].Cells[2].Value = LL_TAIL.ToString("F3");
                dgv.Rows[idx].Cells[3].Value = LL_DELTA.ToString("F3");

                time = time.AddMinutes(minutes);
            }
        }

        public static double Calculate(List<AjaxMiscValue> data, long millis, long offset)
        {
            long begin = millis;
            long end = millis + offset;

            double result = 0.0;

            foreach (var v in data)
            {

                if (v.timestamp >= begin && v.timestamp < end)
                {
                    result += v.value;
                }                
            }

            return result;

        }

        public static double SearchNear(List<AjaxMiscValue> data, long millis, long offset)
        {
            AjaxMiscValue found = null;

            long delta = long.MaxValue;

            foreach (var v in data)
            {

                var d = Math.Abs(v.timestamp - millis);
                if (d > offset)
                    continue;

                if (double.IsNaN(v.value))
                    continue;

                if (d < delta)
                {
                    found = v;
                    delta = d;
                }
                else
                {
                    break;
                }
            }

            if (found == null)
            {
                return double.NaN;
            }
            else
            {
                return found.value;
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            ExportCSV.export(this.dataGridView1);
        }
    }
}
